package com.woniuxy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.admin.exception.ScoreException;
import com.woniuxy.admin.entity.AdminInfo;
import com.woniuxy.admin.entity.ScoreDiscount;
import com.woniuxy.admin.mapper.AdminInfoMapper;
import com.woniuxy.admin.mapper.ScoreDiscountMapper;
import com.woniuxy.admin.service.ScoreDiscountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ...
 * @since 2024年05月22日
 */
@Service
public class ScoreDiscountServiceImpl extends ServiceImpl<ScoreDiscountMapper, ScoreDiscount> implements ScoreDiscountService {

    @Resource
    private AdminInfoMapper adminInfoMapper;

    /**
     * 更新抵扣规则
     * @param discountRatio 抵扣比例1分抵扣多少钱
     * @param accountId 账户id
     */
    @Override
    public void updateScoreDiscount(BigDecimal discountRatio, Integer accountId) {
        if(discountRatio.compareTo(BigDecimal.ZERO)<0){
            throw new ScoreException(10001,"积分抵扣比例不能小于0");
        }
        List<ScoreDiscount> list = this.list();
        AdminInfo adminInfo = adminInfoMapper.selectOne(new QueryWrapper<AdminInfo>().eq("account_id", accountId));
        if(list==null&&list.size()==0){
            ScoreDiscount scoreDiscount = new ScoreDiscount();
            scoreDiscount.setDiscountRatio(discountRatio);
            scoreDiscount.setModifyBy(adminInfo.getRealName());
            scoreDiscount.setModifyTime(LocalDateTime.now());
            this.save(scoreDiscount);
        }
        ScoreDiscount scoreDiscount = list.get(0);
        scoreDiscount.setDiscountRatio(discountRatio);
        scoreDiscount.setModifyBy(adminInfo.getRealName());
        scoreDiscount.setModifyTime(LocalDateTime.now());
        this.updateById(scoreDiscount);
    }
}
